<template>
  <div class="course-detail-container">
    <el-card v-if="courseDetail" class="course-detail-card">
      <template #header>
          <div class="card-header">
            <span>{{ courseDetail.name }}</span>
          </div>
        </template>
      
      <!-- 课程基本信息 -->
      <div class="course-info">
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">课程简介：</span>
            <span class="info-value">{{ courseDetail.intro || courseDetail.description || '暂无简介' }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">授课老师：</span>
            <span class="info-value">{{ courseDetail.teacher || courseDetail.teacherName || '暂无信息' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">开始上课时间：</span>
            <span class="info-value">{{ formatDate(courseDetail.classTime || courseDetail.startTime) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">结束时间：</span>
            <span class="info-value">{{ formatDate(courseDetail.endTime) || '暂无信息' }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <span class="info-label">所属类别：</span>
            <span class="info-value">{{ courseDetail.categoryName || '暂无信息' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">创建者：</span>
            <span class="info-value">{{ courseDetail.userId || '系统管理员' }}</span>
          </div>
        </div>
      </div>
      
      <!-- 标签页组件 -->
      <el-tabs v-model="activeTab" type="border-card" style="margin-top: 20px;" @tab-change="handleTabChange">
        <el-tab-pane label="课程内容" name="content">
          <div class="course-content">
            <h3>课程任务列表</h3>
            <div v-if="tasks.length > 0" class="tasks-list">
              <el-table :data="tasks" style="width: 100%">
                <el-table-column prop="name" label="任务名称" width="200"></el-table-column>
                <el-table-column prop="description" label="任务描述"></el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                  <template #default="scope">
                  <el-button type="primary" size="small" @click="completeTask(scope.row.id)">完成</el-button>
                </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="no-tasks">
              <el-empty description="暂无任务项"></el-empty>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="课程评价" name="comments">
            <div class="course-comments">
              <!-- 评价列表 -->
              <div class="comments-section">
                <h3>课程评价 ({{ commentList.length }})</h3>
                <div v-if="commentList.length > 0" class="comments-list">
                  <div v-for="comment in commentList" :key="comment.id" class="comment-item">
                    <el-card class="comment-card" shadow="hover">
                      <div class="comment-header">
                        <div class="comment-author">
                          <el-avatar :size="32" :src="comment.avatar" />
                          <span class="author-name">{{ comment.authorName }}</span>
                        </div>
                        <span class="comment-time">{{ formatDate(comment.addedTime) }}</span>
                      </div>
                      <div class="comment-body">
                        <p>{{ comment.body }}</p>
                      </div>
                    </el-card>
                  </div>
                </div>
                <div v-else class="no-comments">
                  <el-empty description="暂无评价"></el-empty>
                </div>
              </div>
              
              <!-- 添加评价表单 -->
              <div class="add-comment" v-if="userStore.isAuthenticated">
                <h4>发表评价</h4>
                <el-input 
                  v-model="commentContent" 
                  type="textarea" 
                  placeholder="写下您的评价..." 
                  :rows="3"
                  :disabled="isSubmitting"
                ></el-input>
                <el-button 
                  type="primary" 
                  @click="submitComment" 
                  style="margin-top: 10px;"
                  :loading="isSubmitting"
                >
                  提交评价
                </el-button>
              </div>
              <div v-else class="login-prompt">
                <el-button type="text" @click="goToLogin">登录后发表评价</el-button>
              </div>
            </div>
          </el-tab-pane>
      </el-tabs>
      
      <div class="action-buttons" style="margin-top: 20px;">
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
    
    <div v-else class="loading-state">
      <el-progress type="circular" :percentage="100" status="warning" />
      <p>加载课程信息中...</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { api } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'CourseDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    
    const courseDetail = ref(null)
    const tasks = ref([])
    const commentList = ref([])
    const activeTab = ref('content')
    const commentContent = ref('')
    const isSubmitting = ref(false)
    
    // 格式化日期
    const formatDate = (timestamp) => {
      if (!timestamp) return '暂无信息'
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
    
    // 获取课程详情
    const fetchCourseDetail = async () => {
      const courseId = route.params.id
      try {
        // 调用getsingle接口获取课程详情，typeIndex=6
        const response = await api.items.getSingle(courseId, 6)
        
        if (response) {
          // 标准化课程数据
          courseDetail.value = {
            id: response.id,
            name: response.name || response.title || '未命名课程',
            intro: response.body || response.description || '暂无简介',
            teacher: response.teacher || response.teacherName || '暂无信息',
            classTime: response.startTime || response.classTime,
            endTime: response.endTime,
            timestamp: response.startTime ? new Date(response.startTime).getTime() : Date.now(),
            categoryName: response.categoryName || '暂无信息',
            userId: response.userid || response.userId || '系统管理员'
          }
          
          console.log('课程详情数据:', courseDetail.value)
          
          // 同步获取课程任务项
          await fetchCourseTasks(courseId)
        } else {
          ElMessage.error('课程不存在')
          router.push('/')
        }
      } catch (error) {
        console.error('获取课程详情失败:', error)
        ElMessage.error('获取课程详情失败，请稍后重试')
      }
    }
    
    // 获取评价列表
    const fetchComments = async (courseId) => {
      if (!courseId) return
      console.log('开始获取课程评价，课程ID:', courseId)
      
      try {
        // 使用api.items.getAll方法，typeIndex=4对应comments表
        const response = await api.items.getAll(4, { 
          articleid: courseId, 
          replyType: '课程' 
        })
        
        console.log('评价API响应原始数据:', response)
        
        // 处理响应数据
        let commentData = []
        if (Array.isArray(response)) {
          commentData = response
        } else if (response && response.errno === 0 && Array.isArray(response.data)) {
          commentData = response.data
        } else if (response && response.data && Array.isArray(response.data)) {
          commentData = response.data
        }
        
        console.log('处理后的评价数据:', commentData)
        
        // 标准化评价数据，确保每个字段都存在
        commentList.value = commentData.map(comment => ({
          id: comment.id || Math.random().toString(36).substr(2, 9), // 确保有ID
          authorName: comment.authorName || comment.userid || '匿名用户',
          body: comment.body || comment.content || '暂无内容', // 处理可能的不同字段名
          addedTime: comment.addedTime || comment.createTime || Date.now(),
          avatar: `https://cube.elemecdn.com/${Math.floor(Math.random() * 3)}/88/03b0d39583f48206768a7534e55bcpng.png`
        }))
        
        console.log('标准化后的评价列表:', commentList.value)
        
        if (commentList.value.length === 0) {
          ElMessage.info('暂无评价数据')
        } else {
          ElMessage.success(`成功获取到${commentList.value.length}条评价`)
        }
      } catch (error) {
        console.error('获取课程评价失败:', error)
        ElMessage.error('获取评价失败，请稍后重试')
        commentList.value = [] // 确保出错时也是空数组
      }
    }
    
    // 获取课程任务项
    const fetchCourseTasks = async (courseId) => {
      try {
        // 调用getallitems接口获取任务项列表，typeIndex=7，带courseId参数
        const response = await api.items.getAll(7, { parentid: courseId, parentType: '课程' })
        
        if (response && response.length > 0) {
          // 标准化任务数据
          tasks.value = response.map(task => ({
            id: task.id,
            name: task.title || task.name || '未命名任务',
            description: task.body || task.description || '暂无描述',
            courseId: courseId
          }))
          
        } else {
          tasks.value = []
        }
      } catch (error) {
        console.error('获取课程任务项失败:', error)
        tasks.value = []
      }
    }
    
    // 完成任务
    const completeTask = (taskId) => {
      ElMessage.success('已完成任务ID：' + taskId)
    }
    
    // 提交评价
    const submitComment = async () => {
      if (!commentContent.value.trim()) {
        ElMessage.warning('评价内容不能为空')
        return
      }
       
      // 验证登录状态
      if (!userStore.isAuthenticated || !userStore.userInfo) {
        ElMessage.warning('请先登录')
        router.push('/login')
        return
      }
       
      const courseId = route.params.id
      isSubmitting.value = true
       
      try {
        // 准备提交的数据 - 确保字段与后端comments表结构匹配
        const submitData = {
          body: commentContent.value.trim(),
          userid: userStore.userInfo?.id,
          replyType: '课程',
          articleid: parseInt(courseId)
        };
        
        console.log('准备提交的评价数据:', submitData);
        console.log('表索引: 4 (comments表)');
        
        // 使用API调用方式
        const response = await api.items.add(submitData, 4);
        
        console.log('提交响应:', response);
        
        if (response && response.success !== false) {
          // 提交成功后重新获取评价列表
          await fetchComments(courseId)
          commentContent.value = ''
          ElMessage.success('评价提交成功！');
        } else {
          ElMessage.error(response?.message || '评价提交失败，请重试！');
        }
      } catch (error) {
        console.error('提交评价失败:', error);
        if (error.response) {
          ElMessage.error(`提交失败: ${error.response.data?.message || error.response.statusText}`);
        } else if (error.message) {
          ElMessage.error(`提交失败: ${error.message}`);
        } else {
          ElMessage.error('提交失败，请检查网络连接！');
        }
      } finally {
        isSubmitting.value = false
      }
    }
    
    // 跳转到登录页
    const goToLogin = () => {
      router.push('/login')
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 切换标签页时获取评价列表
    const handleTabChange = async (tabName) => {
      console.log('标签页切换为:', tabName)
      if (tabName === 'comments') {
        console.log('切换到评价标签页，开始获取评价数据')
        await fetchComments(route.params.id)
      }
    }
    
    // 组件挂载时获取课程详情
    onMounted(async () => {
      await fetchCourseDetail()
      // 直接获取评价数据
      if (route.params.id) {
        await fetchComments(route.params.id)
      }
    })
    
    return {
      courseDetail,
      tasks,
      commentList,
      isSubmitting,
      activeTab,
      commentContent,
      userStore,
      formatDate,
      completeTask,
      submitComment,
      goToLogin,
      goBack,
      handleTabChange
    }
  }
}
</script>

<style scoped>
.course-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.course-detail-card {
  margin-bottom: 2rem;
}

.card-header {
  font-size: 1.5rem;
  font-weight: bold;
}

.course-info {
  margin-bottom: 2rem;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.info-row {
  display: flex;
  margin-bottom: 1rem;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: flex-start;
  margin-right: 2rem;
}

.info-label {
  font-weight: bold;
  color: #606266;
  min-width: 100px;
}

.info-value {
  color: #303133;
  flex: 1;
  word-break: break-word;
}

.course-content h3,
.course-comments h3 {
  margin-bottom: 1rem;
  color: #303133;
  font-size: 1.2rem;
}

.tasks-list,
.comments-list {
  margin-bottom: 1rem;
}

.no-tasks,
.no-comments {
  text-align: center;
  padding: 2rem;
}

.add-comment {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #ebeef5;
}

.login-prompt {
  margin-top: 1rem;
  text-align: center;
  color: #909399;
}

.action-buttons {
  margin-top: 2rem;
  display: flex;
  justify-content: flex-start;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
}

.loading-state p {
  margin-top: 1rem;
  color: #909399;
}

/* 评价相关的样式优化 */
.comments-section {
  margin-bottom: 20px;
}

.comment-item {
  margin-bottom: 16px;
}

.comment-card {
  padding: 16px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.comment-author {
  display: flex;
  align-items: center;
}

.author-name {
  margin-left: 12px;
  font-weight: bold;
  color: #303133;
}

.comment-time {
  color: #909399;
  font-size: 0.85rem;
}

.comment-body {
  color: #606266;
  line-height: 1.5;
}

.add-comment {
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.add-comment h4 {
  margin-bottom: 12px;
  color: #303133;
}

.el-textarea__inner {
  min-height: 120px;
  resize: vertical;
}

.login-prompt {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

@media (max-width: 768px) {
  .course-detail-container {
    padding: 1rem;
  }
  
  .info-row {
    flex-direction: column;
  }
  
  .info-item {
    margin-right: 0;
    margin-bottom: 1rem;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .comment-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .comment-time {
    margin-top: 4px;
  }
}
</style>